package com.mayfool.task.service.cvs;

import com.mayfool.task.bo.RemoteBO;
import com.mayfool.task.enums.CvsTypeEnum;
import com.mayfool.task.service.CvsService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.RemoteListCommand;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.transport.RemoteConfig;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhou.xu 2024/8/27 19:31
 */
@Service
@Slf4j
public class GitService implements CvsService {

    @Override
    public CvsTypeEnum getCvsType() {
        return CvsTypeEnum.GIT;
    }

    @Override
    public List<RemoteBO> listRemote(String gitDir) {
        List<RemoteBO> result = new ArrayList<>();
        try {
            FileRepository fileRepository = new FileRepository(gitDir);
            Git git = new Git(fileRepository);
            RemoteListCommand command = git.remoteList();
            List<RemoteConfig> call = command.call();
            for (RemoteConfig remoteConfig : call) {
                RemoteBO remoteBO = new RemoteBO()
                        .setRemoteName(remoteConfig.getName())
                        .setRemoteUrl(remoteConfig.getURIs().get(0).toString());
                result.add(remoteBO);
            }
        } catch (Exception e) {
            log.error("git list remote error", e);
        }
        return result;
    }
}
